package com.dvj.demo.mbp.gen;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;

import java.io.File;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

/**
 * MybatisGenUtils
 * 代码生成
 *
 * @author Dvj
 * @date 2021/5/26 11:57
 */
public class MybatisGenUtils {

    public static void main(String[] args) {
        codeCreate(new GenInfo());
    }

    /**
     * 读取控制台内容
     */
    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入" + tip + "：");
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StrUtil.isNotEmpty(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "！");
    }

    /**
     * 代码生成
     *
     * @param genInfo 代码生成器配置
     */
    public static void codeCreate(GenInfo genInfo) {
        System.out.println("-------开始生成代码-------");
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        gc.setFileOverride(genInfo.getOverrideExistFile())
                .setEnableCache(false)
                .setBaseResultMap(true)
                .setBaseColumnList(true)
                .setOutputDir(genInfo.getProjectPath())
                .setAuthor(genInfo.getAuthor())
                .setSwagger2(true)
                .setOpen(false);

        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl(genInfo.getUrl());
        dsc.setDriverName(genInfo.getDriverName());
        dsc.setUsername(genInfo.getUserName());
        dsc.setPassword(genInfo.getPassword());
        mpg.setDataSource(dsc);

        //自定义配置,必须配置,不然报错
        mpg.setCfg(new InjectionConfig() {
            @Override
            public void initMap() {
                //空的
            }
        });

        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setParent(null)
                .setController(genInfo.getGenController() ? genInfo.getControllerPackageName() : "TTT")
                .setService(genInfo.getGenService() ? genInfo.getServicePackageName() : "TTT")
                .setServiceImpl(genInfo.getGenService() ? genInfo.getServiceImplPackageName() : "TTT")
                //配置dao包名
                .setEntity(genInfo.getEntityPackageName())
                .setMapper(genInfo.getMapperPackageName())
                .setXml(genInfo.getXmlPackageName());
        mpg.setPackageInfo(pc);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setEntityLombokModel(true)
                .setRestControllerStyle(true)
                // 此处可以修改为您的表前缀
                .setTablePrefix(genInfo.getTablePrefix())
                .setNaming(NamingStrategy.underline_to_camel)
                .setInclude(scanner("表名，多个英文逗号分割").split(","));
        mpg.setStrategy(strategy);

        showTables(dsc, genInfo.getDbName());

        mpg.execute();

        destroy(gc);

        System.out.println();
        System.out.println("-------代码生成完成-------");
    }


    /**
     * 删除不必要的代码
     */
    public static void destroy(GlobalConfig globalConfig) {
        String outputDir = globalConfig.getOutputDir() + "/TTT";
        FileUtil.del(new File(outputDir));
    }

    /**
     * 显示所有表名,这里查询了注释
     *
     * @param dsc    数据源配置
     * @param dbName 数据库名
     */
    public static void showTables(DataSourceConfig dsc, String dbName) {
        try {
            ResultSet resultSet = dsc.getConn().createStatement().executeQuery("select TABLE_NAME as tableName,TABLE_COMMENT as tableComment from information_schema.`TABLES` where TABLE_SCHEMA = '" + dbName + "'");
            while (resultSet.next()) {
                String tableName = resultSet.getString(1);
                System.err.println(tableName);
            }
            System.err.println("---------------------------");
            System.err.println();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
